package com.gton.lpl.common.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.gton.lpl.common.diyerror.MyLoginException;
import com.gton.lpl.common.service.OSSCommonServer;
import com.gton.lpl.common.tools.CommonStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @description: OSS操作
 * @author: GuoTong
 * @createTime: 2022-08-16 21:55
 * @since JDK 1.8 OR 11
 **/
@Service
@Slf4j
public class OSSCommonServerImpl implements OSSCommonServer {

    @Value("${aliyun.oss.endpoint:https://oss-cn-beijing.aliyuncs.com}")
    private String endpoint;

    // 阿里云账号AccessKey
    @Value("${aliyun.oss.accessKeyId:LTAI4GKRM6xc255H8aRJBTYu}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret:OPDBk44sSDeZsIEP7NVGAAMq9cJJ9c}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName:edu-gt}")
    private String bucketName;


    /**
     * Description:  判断文件是否存在
     *
     * @param keyName
     * @param isINoss
     * @author: GuoTong
     * @date: 2022-08-16 22:07:55
     * @return:boolean
     */
    public boolean fileIsExist(String keyName, boolean isINoss) {
        boolean resp = false;
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //keyName -> 不包含Bucket名称在内的Object完整路径，例如 exampleobject.txt。
            if (isINoss) {
                //设置是否进行重定向或者镜像回源。默认值为true，表示忽略302重定向和镜像回源
                resp = ossClient.doesObjectExist(bucketName, keyName, isINoss);
                return resp;
            }
            resp = ossClient.doesObjectExist(bucketName, keyName);
        } catch (OSSException e) {
            log.error("OSSException->>>>>" + e.getMessage());
            e.printStackTrace();
        } catch (ClientException e) {
            log.error("OSSSClient 出错了!" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return resp;
    }


    /**
     * Description: 文件上传OSS
     *
     * @param multipartFile 上传文件
     * @param userKey       用户唯一上传的Key
     * @author: GuoTong
     * @date: 2022-08-20 15:54:19
     * @return:java.lang.String 文件的保存的URL
     */
    @Override
    public String singleFileUploadOSS(MultipartFile multipartFile, String userKey) {

        OSS ossClient = getOSSClient();
        StringBuilder updateUrl = new StringBuilder();
        try {
            // 获取文件名称||避免有中文名字的
            String originalFilename = multipartFile.getOriginalFilename();
            String[] split = originalFilename.split("\\.");
            if (split.length < 1) {
                throw new MyLoginException("文件格式不对");
            }
            String fileSuffix = split[split.length - 1];
            //获取文件输入流
            InputStream inputStream = multipartFile.getInputStream();
            //构建日期文件夹
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(CommonStringUtils.DATE_TIME_TYPE);
            String format = now.format(dateTimeFormatter);
            String fileName = UUID.randomUUID().toString().replace("-", "");
            //构建文件最终存放位置
            updateUrl.append(format).append("/").append(userKey).append("/").append(fileName).append(".").append(fileSuffix);
            // 创建PutObject请求。
            ossClient.putObject(bucketName, updateUrl.toString(), inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        updateUrl.insert(0, "https://edu-gt.oss-cn-beijing.aliyuncs.com/");
        return updateUrl.toString();
    }

    @Override
    public OSS getOSSClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }


}
